package org.csu.hotelsys.validator;

import org.csu.hotelsys.model.Roomkt;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.Objects;

import static org.csu.hotelsys.helpers.InputValidatorHelpers.isHtmlSafe;

@Component("roomValidator")
public class RoomValidator implements Validator {

    @Override
    public boolean supports(@NotNull Class<?> clazz) {
        return Roomkt.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(@NotNull Object target, @NotNull Errors errors) {
        Roomkt roomkt = (Roomkt) target;

        ValidationUtils.rejectIfEmpty(errors, "name", "room.name.empty");
        ValidationUtils.rejectIfEmpty(errors, "price", "room.price.empty");
        ValidationUtils.rejectIfEmpty(errors, "capacity", "room.capacity.empty");

        // check for field injection
        if (isHtmlSafe(roomkt.getDescription())) {
            errors.rejectValue("description", "field.notallowed");
        }
        if (isHtmlSafe(roomkt.getName())) {
            errors.rejectValue("name", "field.notallowed");
        }
        if (isHtmlSafe(Objects.requireNonNull(roomkt.getBed()).toString())) {
            errors.rejectValue("bed", "field.notallowed");
        }
        if (isHtmlSafe(Objects.requireNonNull(roomkt.getCapacity()).toString())) {
            errors.rejectValue("capacity", "field.notallowed");
        }
        if (isHtmlSafe(Objects.requireNonNull(roomkt.getPrice()).toString())) {
            errors.rejectValue("price", "field.notallowed");
        }
    }
}
